<template>
  <div>
    <div class="header">
      <div class="top">
        <div class="logo">
          <img src="https://i01.lw.aliimg.com/media/lALPBY0V4x3hbePNAdzNAdw_476_476.png" alt="" />
        </div>
        <Seach />
      </div>
      <Login />
    </div>
    <el-container style="margin-top: 60px">
      <el-aside width="250px">
        <el-menu default-active="1" router active-text-color="#ec4141">
          <el-menu-item-group>
            <template slot="title">
              <div style="font-size: 15px">推荐</div>
            </template>
            <el-menu-item index="1" route="/pageOne/recommend">
              发现音乐</el-menu-item>
            <el-menu-item index="2" route="/pageTwo/videoRec">推荐视频</el-menu-item>
            <div class="el-menu-item-group__title" v-if="list.length > 0">
              <div style="font-size: 15px">创建的歌单</div>
            </div>

            <el-menu-item v-for="(item, index) in list" :key="index">
              <div class="listName" @click="getItem(item.id)" @contextmenu.prevent="memu(item)">
                <el-image :src="item.coverImgUrl"></el-image>{{ item.name }}
              </div>
            </el-menu-item>

            <div v-if="uid !== ''">
              <div class="el-menu-item-group__title">
                <div style="font-size: 15px">我的音乐云盘</div>
              </div>

              <el-menu-item index="3" route="/LikePage">
                我的音乐云盘
              </el-menu-item>
            </div>

            <div class="el-menu-item-group__title" v-if="list2.length > 0">
              <div style="font-size: 15px">收藏的歌单</div>
            </div>

            <div style="margin-bottom:40px">
              <el-menu-item v-for="(item, index) in list2" :key="index">
                <div class="listName" @click="getItem(item.id)">
                  <el-image :src="item.coverImgUrl"></el-image>{{ item.name }}
                </div>
              </el-menu-item>
            </div>
          </el-menu-item-group>
        </el-menu>
      </el-aside>
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
    <PlayBar />

    <!-- 加入机器人 -->
    <div v-if="cookie !== ''">
      <Ai />
    </div>


    <el-dialog title="编辑歌单" :visible.sync="dialogVisible" width="400px" :before-close="handleClose">
      <el-form :model="createForm" ref="createFormRef" class="demo-ruleForm">

        <el-form-item label="更新歌单名" prop="name">
          <el-input v-model="createForm.name" size="medium"></el-input>
        </el-form-item>

        <el-form-item label="更新歌单描述" prop="desc">
          <el-input v-model="createForm.desc" size="medium"></el-input>
        </el-form-item>
      </el-form>
      <!-- 图片上传 -->
      <div>上传图片</div>
      <div class="imgBox">
        <div class="upload">
          <input type="file" id="file" @change="upload">
        </div>
        <li v-for="(item, index) in pic" :key="index" class="img">
          <img :src="item">
          <div class="delect" @click="delect(index)">×</div>
        </li>
      </div>
      <el-button type="danger" @click="confirm()">确定</el-button>
      <el-button type="danger" @click="del()">删除歌单</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  components: {
    Login: () => import('../components/LoginBar.vue'),
    PlayBar: () => import('../components/playBar.vue'),
    Ai: () => import('../components/smartAi.vue'),
    Seach: () => import('../components/seachBox.vue'),
  },
  computed: {
    ...mapState(['userList', 'songList', 'subList']),
  },
  created() {
    this.$router.push('/pageOne/recommend');
  },
  watch: {
    songList(newVal, oldVal) {
      this.playlist = []
      this.$api.userPlayList({ uid: this.uid, timestamp: this.$utils.timestamp(), cookie: localStorage.getItem('cookie') }).then((ret) => {
        for (let i = 0; i < ret.playlist.length; i++) {
          if (ret.playlist[i].creator.userId === parseInt(this.uid)) {
            this.playlist.push(ret.playlist[i])
          } else {
            continue
          }
        }
        this.saveUserList({ userList: this.playlist })
      })
    },
    userList(newVal, oldVal) {
      this.list = []
      this.list = newVal.userList
      this.cookie = localStorage.getItem('cookie')
      this.uid = localStorage.getItem('uid')
    },
    subList(newVal, oldVal) {
      this.list2 = []
      this.list2 = newVal.subList
    },

  },

  data() {
    return {
      uid: '',
      cookie: '',
      list: [],
      list2: [],
      playlist: [],
      dialogVisible: false,
      checked: false,
      createForm: {
        name: '',
        desc: '',
      },
      imageUrl: '',
      pic: [],
      data: '',
      formdata: '',
      width: '',
    };
  },
  methods: {
    ...mapActions(['saveSongList', 'clickPlay', 'saveNowSongCount', 'saveNowSong', 'saveUserList']),
    // 跳转到歌单明细
    async getItem(e) {
      this.loading = true;
      this.$api.getPlayList({ id: e, cookie: this.cookie, timestamp: this.$utils.timestamp(), cookie: localStorage.getItem('cookie') }).then((ret) => {
        if (ret.code === 200) {
          this.saveSongList({ songList: ret.playlist }); // 获取到的明细存入VUEX
          this.$router.push(`/songList?id=${e}`);
          this.clickPlay({ ifPlay: true });
        } else {
          this.$message.error('超时获取失败!!!');
        }
      });
    },

    memu(e) {
      this.data = e
      this.createForm.name = e.name
      this.createForm.desc = e.desc
      this.$api.getPlayList({ id: e.id, cookie: this.cookie, timestamp: this.$utils.timestamp() }).then((ret) => {
        this.createForm.desc = ret.playlist.description
      });
      this.dialogVisible = true
    },

    handleClose() {
      this.dialogVisible = false
    },

    confirm() {
      if (this.createForm.name !== '') {
        // 更新歌单名称
        this.$api.updateName({ id: this.data.id, name: this.createForm.name, cookie: this.cookie, timestamp: this.$utils.timestamp() }).then((ret) => {
          if (ret.code === 200) {
            this.getUserList()
            this.$message({
              message: '操作成功',
              type: 'success',
            });
          }
        })
      }

      if (this.createForm.desc !== '') {
        // 更新歌单描述
        this.$api.updateDesc({ id: this.data.id, desc: this.createForm.desc, cookie: this.cookie, timestamp: this.$utils.timestamp() }).then((ret) => {
          if (ret.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
            });
          }
        })
      }


      if (this.formdata !== '') {
        // 更新歌单封面
        this.$api.updateImg({ id: this.data.id, cookie: this.cookie, timestamp: this.$utils.timestamp(), imgFile: this.formdata, imgSize: this.width.width }).then((ret) => {
          if (ret.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
            });
            this.pic = []
            this.getUserList()
          }
        })
      }

      this.$api.getPlayList({ id: this.data.id, cookie: this.cookie, timestamp: this.$utils.timestamp() }).then((ret) => {
        if (ret.code === 200) {
          this.saveSongList({ songList: ret.playlist }); // 获取到的明细存入VUEX
        }
      });

      this.dialogVisible = false
    },

    async upload(e) {
      this.pic = []
      for (const item of e.target.files) {
        if (!/image\/\w+/.test(item.type)) {
          // 提示只能是图片，return
          alert('只能选择图片');
          return;
        }
        var _this = this;
        const reader = new FileReader();
        reader.readAsDataURL(item);
        reader.addEventListener('load', function () {
          _this.pic.push(this.result)
        })
        this.formdata = new FormData()
        this.formdata.append('imgFile', e.target.files[0]) // 将每一个文件图片都加进formdata
        this.width = await this.$utils.getImgSize(e.target.files[0])
      }
    },

    delect(index) {
      this.pic.splice(index, 1);
    },

    getUserList() {
      const playlist = []
      this.$api.userPlayList({ uid: this.uid, timestamp: this.$utils.timestamp(), cookie: localStorage.getItem('cookie') }).then((ret) => {
        for (let i = 0; i < ret.playlist.length; i++) {
          if (ret.playlist[i].creator.userId === parseInt(this.uid)) {
            playlist.push(ret.playlist[i])
          } else {
            continue
          }
        }
        this.saveUserList({ userList: playlist })
      })
    },

    del() {
      this.$confirm('此操作将永久删除此歌单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$api.delSongList({ id: this.data.id, cookie: this.cookie, timestamp: this.$utils.timestamp() }).then((ret) => {
          if (ret.code === 200) {
            this.getUserList()
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          }
          this.dialogVisible = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        });
      });
    },

  },
};
</script>

<style scoped>
.el-menu {
  width: 250px;
  position: fixed;
  border: none;
  top: 60px;
  height: 90%;
  overflow-y: scroll;
}

.el-aside {
  border-right: solid 1px #e6e6e6;
  margin-bottom: 60px;
}

.header {
  height: 60px;
  background: #ec4141;
  display: flex;
  align-items: center;
  position: fixed;
  top: 0;
  z-index: 100;
  width: 100%;
  justify-content: space-between;
}

.top {
  display: flex;
  align-items: center;
}

.logo {
  width: 50px;
  height: 50px;
  margin-left: 20px;
  margin-right: 10px;
}

.logo img {
  width: 50px;
  height: 50px;
}

.el-menu-item {
  font-size: 20px;
}

.listName {
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-image {
  width: 50px;
  height: 50px;
  margin-right: 10px;
}


.img img {
  width: 80px;
  height: 80px;
}

.img {
  margin-left: 10px;
  position: relative;
}

.imgBox {
  display: flex;
  align-items: center;
}

li {
  list-style: none;
}

.upload {
  width: 80px;
  height: 80px;
  border: 1px dashed black;
  border-radius: 5px;
  position: relative;
  margin-top: 10px;
  margin-bottom: 10px;
}

.upload::before {
  position: absolute;
  top: 30px;
  left: 0;
  right: 0;
  bottom: 0;
  content: '+';
  font-size: 20px;
  text-align: center;
  line-height: 20px;
  user-select: none;
}

#file {
  width: 100%;
  height: 100%;
  opacity: 0;
}

.delect {
  position: absolute;
  right: 0;
  top: 0;
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  font-size: 15px;
  background-color: rgba(255, 255, 255, 0.5);
  user-select: none;
  cursor: pointer;
  opacity: 0;
}

.delect:hover {
  background-color: rgba(31, 31, 31, 0.5);
  color: white;
}

.img .delect {
  opacity: 1;
}

body::-webkit-scrollbar {
  display: none;
}

ul::-webkit-scrollbar {
  display: none;
}
</style>
